/*
 * File Name: ShareAppAction.java
 * Created on: 
 */

package co.edu.uniandes.intercon.client.action;

import java.io.File;
import java.util.List;
import java.util.Map;

import co.edu.uniandes.intercon.core.model.ApplicationDto;
import co.edu.uniandes.intercon.core.model.EApplicationType;
import co.edu.uniandes.intercon.core.model.EMessageType;
import co.edu.uniandes.intercon.core.model.LocalApplicationList;
import co.edu.uniandes.intercon.core.model.P2PMessage;
import co.edu.uniandes.intercon.core.model.ParamDto;
import co.edu.uniandes.intercon.server.core.Constants;
import co.edu.uniandes.intercon.server.networking.UDPSender;
import co.edu.uniandes.intercon.server.util.ConnectionHelper;

/**
 * Action used to start the communication to the system
 * 
 * @author Fabian Gutierrez [fagossa@gmail.com]
 */
public class ShareAppAction extends AbstractBaseGUIAction {

	/**
	 * @see AbstractBaseGUIAction#execute(Map)
	 */
	public Object execute(Map<String, Object> map) throws RuntimeException {
		ApplicationDto dto = new ApplicationDto(System.currentTimeMillis());
		dto.setName((String) map.get("name"));

		EApplicationType appType = (EApplicationType) map.get("type");
		if (appType == EApplicationType.FILE) {
			dto.setType(EApplicationType.FILE);
			String fileName = (String) map.get("fileName");
			dto.setFilePath(fileName);
			dto.setFileSize(getFileSize(fileName));
		} else if (appType == EApplicationType.PROCESS) {
			dto.setType(EApplicationType.PROCESS);
			dto.setImplClass(map.get("process").getClass().getCanonicalName());
		}
		dto.setHost(ConnectionHelper.getCurrentHost());
		dto.setPort(Constants.TCP_PORT);
		dto.setParams((List<ParamDto>) map.get("params"));
		
		LocalApplicationList.getInstance().addMessage(dto);
		
		P2PMessage message = new P2PMessage(dto, EMessageType.ADD);

		if (UDPSender.isConnected()) {
			UDPSender.send(message);
		}

		return dto;
	}

	/*
	 * Retrieve the amount of bytes of the file withe the current name
	 */
	private String getFileSize(String fileName) {
		File f = new File(fileName);
		return String.valueOf(f.length()) + " bytes";
	}

}
